/**
 * 该插件为表单插件
 */
var arrP = [];
//var arrC = [];
function AddrTempParam(p, c) {
    this.p = p;
    this.c = c;
}
(function ($) {
    $.mrdForm = $.mrdForm || {};
    var isSelectState = true;
    var isfocusState = false;
    $.extend($.mrdForm, {
        formContainerId: null,
        formId: null,
        allCoulumns: null,
        formDefaultData: null,
        mrdFormSettings: {},
        defaultSettings: {
            'title': "",// 表单标题
            'module': 'query',// 表单模式 分成查询模式(query)和保存模式(save)
            'numCount': 3,// 每行多少个控件
            'columnNum': 6,// 暂时无用
            'width': "100%",// 表格宽度
            'height': '30',// 一行的高度
            'lwidth': '100',// label的默认宽度
            'cwidth': '250',// 输入框的默认宽度
            'lalign': "right",// label的默认水平位置(居左，居右，居中)
            'lvalign': "middle",// label的默认垂直位置(居上，居下，居中)
            'calign': "left",// 输入框的默认水平位置(居左，居右，居中)
            'cvalign': "middle",// 输入框的默认垂直位置(居上，居下，居中)
            'fieldsets': [],// 数据组合框
            'columns': [],// 字段配置
            'buttons': {},// 按钮配置
            'grid': {},// jqgrid配置
            'form': {}
            // 表单配置
        },
        columnDefaultSettings: {
            'classId': "",
            'name': "",// 输入框id/name
            'label': "",// label名称
            //'type' : columnSetting.password?"password":"text",
            'type': "text",// 输入框类型(text,textarea,dropdown,date)
            'value': "",// 默认值
            'colspan': "",// 输入框占据的空间
            'operator': "cn",// 查询操作符(已废弃)
            'op': "cn",// 查询操作符
            'height': null,// 高度
            'cwidth': null,// 输入框的宽度
            'lwidth': null,// label的宽度
            'lalign': null,// label的水平位置
            'lvalign': null,// label的垂直位置
            'calgin': null,// 输入框的水平位置
            'cvalign': null,// 输入框的垂直位置
            'hidden': false, // 设置隐藏
            'readonly': false,// 设置只读
            'validate': null
            // 表单验证,validationEngine表单验证参数
        },
        /**
         * 查询模式按钮组
         */
        buttonsDefaultSettingsForQuery: {
            'position': 'right',
            'query': true,// 是否显示查询按钮
            'reset': true,// 是否显示重置按钮
            'queryEvent': null,// 重写查询点击事件
            'resetEvent': null,// 重写重置点击事件，不在允许重写重置按钮
            'order': 'queryButton,resetButton',// 查询和重置的排序,暂时未启用
            'custom': []
            // 自定义按钮，内容为按钮对象，具体参考buttonQuery
        },
        /**
         * 保存模式按钮组
         */
        buttonsDefaultSettingsForSave: {
            'position': 'center',
            'save': true,// 是否显示查询按钮
            'reset': false,// 是否显示重置按钮
            'saveEvent': null,// 重写查询点击事件
            'order': 'saveButton,resetButton',// 查询和重置的排序,暂时未启用
            'custom': []
            // 自定义按钮，内容为按钮对象，具体参考buttonQuery
        },
        /**
         * 查询按钮
         */
        buttonQuery: {
            'id': 'queryButton', // 按钮id
            'disabled': false,// 是否禁用
            'value': "查询",// 按钮显示名称
            /**
             * 按钮点击事件
             */
            'click': function () {
                var gridSelect = "#" + $.mrdForm.mrdFormSettings.grid.id;
                var filters = $.mrdForm.filterString();
                // 如果没有查询条件，则返回
                if (!$.mrdForm.isEmpty(filters)) {
                    var postData = $(gridSelect).jqGrid("getGridParam",
                                                        "postData");// 获取将要提交的数据
                    $.extend(postData, {
                        filters: filters
                    });// 将filters插入将要提交的数据
                } else {
                    var postData = $(gridSelect).jqGrid("getGridParam",
                                                        "postData");// 获取将要提交的数据
                    $.extend(postData, {
                        filters: {}
                    });// 将filters插入将要提交的数据
                }
                $(gridSelect).jqGrid("setGridParam", {
                    search: true
                    // 将jqGrid的search选项设为true
                }).trigger("reloadGrid", [{
                    page: 1
                }]); // 重新载入Grid表格
            }
        },
        /**
         * 获取form的jqgrid的filter的字符串组合
         */
        filterString: function () {
            // var gridSelect = "#" + $.mrdForm.mrdFormSettings.grid.id;
            var rules = "";// 定义rules
            var columns = this.mrdFormSettings.columns;// 获取表格配置
            $.each(
                //$("#" + $.mrdForm.formContainerId
                //+ " td[id^='td_control_'] :first-child"), function(i, n) {
                $("#" + $.mrdForm.formContainerId + " td[id^='td_control_'] :first-child,#"
                  + $.mrdForm.formContainerId + " input[type='hidden']"), function (i, n) {
                    var control = $(n);
                    //var control = $(n).children().first();
                    if (!$.mrdForm.isEmpty(control.val())) {
                        var fieldName = control.attr('name');
                        var fieldId = control.attr('id');
                        var op = "";
                        $.each(columns, function (j, m) {
                            //if (m.name == fieldName) {
                            if (m.id == fieldId) {
                                op = m.op;
                            }
                        });
                        if (op == null || op == "") {
                            op = "cn";
                        }
                        rules += "{'field':'" + fieldName + "','op':'" + op
                                 + "','data':'" + control.val() + "'},";// 组装rules
                    }
                });// 如果没有查询条件，则返回
            if (!$.mrdForm.isEmpty(rules)) {
                rules = rules.substring(0, rules.length - 1);
                var filters = '{"groupOp":"AND","rules":[' + rules + ']}';// 定义filters
                return filters;
            } else {
                return "";
            }
        },
        /**
         * 获取form内容的对象
         */
        filterObject: function (objectst) {
            // var gridSelect = "#" + $.mrdForm.mrdFormSettings.grid.id;
            var st = "return ";
            var data = "";
            if (objectst) {
                objectst += ".";
            } else {
                objectst = "";
            }
            $.each(
                $("#" + $.mrdForm.formContainerId
                  + " td[id^='td_control_']"), function (i, n) {
                    var control = $(n).children().first();
                    if (!$.mrdForm.isEmpty(control.val())) {
                        data += "'" + objectst + control.attr('name')
                                + "':'" + control.val() + "',";// 组装rules
                    }
                });// 如果没有查询条件，则返回
            if (data) {
                data = data.substring(0, data.length - 1);
                st = st.concat("{", data, "}");
            } else {
                st = st.concat("{}");
            }
            return (new Function(st))();
        },
        /**
         * 保存按钮
         */
        buttonSave: {
            'id': 'saveButton', // 按钮id
            'disabled': false,// 是否禁用
            'value': "保存",// 按钮显示名称
            'click': function () {
                $("#" + $.mrdForm.formId).submit();
            }
        },
        /**
         * 重置按钮
         *
         */
        buttonReset: {
            'id': 'reset',
            'disabled': false,
            'type': 'button',
            'value': "重置",
            'click': function (event) {
                $(event.srcElement).parents("form").find(":text,:hidden").val("");
            }
        },
        /**
         * jqgrid的默认配置
         */
        defaultGridSettings: {
            id: null,// 表格编号
            url: null,// ajax读取数据的链接
            datatype: "json",// 数据类型
            autowidth: true,// 自动计算宽度
            width: "100%", // 宽度
            height: '100%',// 高度
            scrollOffset: 20,// 浏览器滚动条宽度
            colNames: [],// 标题及排序
            colModel: null,// 字段定义
            mtype: "post",// 提交方式
            multiselect: false,// 是否允许多选
            caption: null,// 标题
            viewrecords: true,// 是否显示数据页数信息
            rowNum: 15,// 分页数
            rowList: [15, 30, 50],// 在pagebar中的可选择分页数大小
            sortname: null,// 排序字段
            prmNames: null,// 分页配置
            jsonReader: {
//                 // 从哪个json对象中取值
//                 root: null,
//                 // 当前页字段名
// //				page : "mrdFormPojo.page.currentPage",
//                 page: "page.currentPage",
//                 // 总页数字段名
// //				total : "mrdFormPojo.page.totlePage",
//                 total: "page.totlePage",
//                 // 总记录数字段名
// //				records : "mrdFormPojo.page.totle",
//                 records: "page.totle",
//                 // 指明每行的数据是可以重复的，如果设为false，则会从返回的数据中按名字来搜索元素，这个名字就是colModel中的名字
                root: "content",
                page: "number",
                total: "totalPages",
                records: "totalElements",
                repeatitems: false
            },
            pager: "#pager",// 分页下标
            pagerpos: "center",// 分页的位置
            // 加载数据失败
            loadError: function (xhr, status, error) {
                var type = xhr.getResponseHeader("Content-Type");
                if (type == "text/javascript") {
                    eval(xhr.responseText);
                }
            },
            afterResponse: function (data) {
                if (data && data['number'] != undefined) {
                    data.number = data.number + 1;
                }
            }
        },
        /**
         * 分页相关配置
         */
        defaultPage_parNames: {
            page: "pageNo", // 表示请求页码的参数名称
            rows: "size", // 表示请求行数的参数名称
            sort: "sidx", // 表示用于排序的列名的参数名称
            order: "sord" // 表示采用的排序方式的参数名称
            // search:"_search", // 表示是否是搜索请求的参数名称
            // nd:"nd", // 表示已经发送请求的次数的参数名称
            // id:"id", // 表示当在编辑数据模块中发送数据时，使用的id的名称
            // oper:"oper", // operation参数名称（我暂时还没用到）
            // editoper:"edit", // 当在edit模式中提交数据时，操作的名称
            // addoper:"add", // 当在add模式中提交数据时，操作的名称
            // deloper:"del", // 当在delete模式中提交数据时，操作的名称
            // subgridid:"id", // 当点击以载入数据到子表时，传递的数据名称
            // npage: null,
            // totalrows:"totalrows" //
            // 表示需从Server得到总共多少行数据的参数名称，参见jqGrid选项中的rowTotal
        },
        /**
         * 按钮的css
         */
        buttonBaseCss: {
            //"font-size" : "80%",
            "margin": "3px"
        },
        defaultFormSettings: {
            url: null,
            data: null,
            validate: null,
            ajaxForm: null,
            afterAjaxSuccess: null
        },
        /**
         * 表单验证的配置
         */
        defaultvalidateSettings: {
            validateType: 'attach',
            options: {
                // 消息位置
                promptPosition: "bottomRight",
                scroll: false
            }
        },
        /**
         * ajaxForm设置
         */
        defaultAjaxFormSettings: {
            // 提交方式
            type: "POST",
            // 提交数据格式
            dataType: "json",
            // 在提交之前做的操作
            beforeSubmit: function () {
                // 进行表达验证,
                return $("#" + $.mrdForm.formId).validationEngine("validate");
            },
            // 成功后做的操作
            success: function (responseText, statusText, xhr, $form) {
                var msg;
                try {
                    msg = responseText.msg;
                } catch (e) {
                    console.log("转换出错，使用旧的使用方法!");
                    msg = $.parseJSON(responseText.msg).msg;
                }
                if (msg) {
                    jw.alert(msg, {
                        onOk: function () {
                            var after = $.mrdForm.mrdFormSettings.form.afterAjaxSuccess;
                            if (after) {
                                after.call(this, responseText, statusText, xhr,
                                           $form);
                            }
                        }
                    });
                    /**
                     * var dialog = $("<div>", { 'id' :
					 * "submit-dialog-message", 'title' : '消息窗口' }).append("
                     * <p>" + msg + "
                     * </p>
                     * "); dialog.appendTo("body");
                     * $("#submit-dialog-message").dialog({ modal : true, close :
					 * function() { var after =
					 * $.mrdForm.mrdFormSettings.form.afterAjaxSuccess; if
					 * (after) { after.call(this, responseText, statusText, xhr,
					 * $form); } }, buttons : [{ 'text' : "确定", 'click' :
					 * function() { $(this).dialog("close"); dialog.remove();
					 * $(this).dialog("destroy"); } }]
					 * }).parent().css($.mrdForm.buttonBaseCss);
                     */
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus == "parsererror") {
                    var type = XMLHttpRequest.getResponseHeader("Content-Type");
                    if (this.dataType == "json" && type == "text/javascript") {
                        eval(XMLHttpRequest.responseText);
                    }
                }
            }
        },
        _initSetting: function (options) {
            var settings = this.mrdFormSettings;
            // 加载form设置
            $.extend(settings, this.defaultSettings, options);
            // 初始化输入框配置
            settings.columns = this._initColumns(settings.columns);
            // 初始化字段框
            settings.fieldsets = this._initFieldSets(settings.fieldsets,
                                                     settings);
            // 初始化按钮组
            if (settings.module == 'save') {
                settings.buttons = $.extend({},
                                            this.buttonsDefaultSettingsForSave, settings.buttons);
            } else {
                settings.buttons = $.extend({},
                                            this.buttonsDefaultSettingsForQuery, settings.buttons);
            }
            // 初始化表格
            if (!this.isEmpty(settings.grid.id)) {
                if (this.isEmpty(settings.grid.colModel)) {
                    $.error("表格配置的字段信息配置不能为空!");
                    return;
                }
                settings.grid = $.extend(true, {}, this.defaultGridSettings,
                                         settings.grid);
                settings.grid.prmNames = $.extend({},
                                                  this.defaultPage_parNames,
                                                  settings.grid.prmNames);
                settings.grid.caption = settings.grid.title;
            }
            // 初始化表单设置
            if (settings.module == 'save') {
                settings.form = $.extend({}, this.defaultFormSettings,
                                         settings.form);
                // 初始化表单验证配置
                settings.form.validate = $.extend({},
                                                  this.defaultvalidateSettings,
                                                  settings.form.validate);
                // 初始化ajax提交配置
                settings.form.ajaxForm = $.extend({},
                                                  this.defaultAjaxFormSettings,
                                                  settings.form.ajaxForm);
            }
            return settings;
        },
        /**
         * 初始化字段框，主要初始化字段
         */
        _initFieldSets: function (fieldsets, settings) {
            if (fieldsets != null && fieldsets.length != 0) {
                $.each(fieldsets, function (i, n) {
                    n.columns = $.mrdForm._initColumns(n.columns);
                    if (n.numCount == undefined || n.numCount == null) {
                        n.numCount = settings.numCount;
                    }
                    if (n.columnNum == undefined || n.columnNum == null) {
                        n.columnNum = settings.columnNum;
                    }
                });
                return fieldsets;
            } else {
                return null;
            }
        },
        /**
         * 初始化输入框配置
         */
        _initColumns: function (columns) {
            var index = 0;
            var tmp = $.map(columns, function (n) {
                if (n.id == undefined || n.id == null || n.id == "") {
                    index++;
                    n.id = "form_in_control_" + index;
                }
                var setting = {};
                $.extend(setting, $.mrdForm.columnDefaultSettings, n);
                switch (setting.type) {
                    case "textarea" :
                        setting = $.mrdForm
                            ._setTextareaSetting(setting);
                        break;
                    case "dropdown" :
                        setting = $.mrdForm
                            ._setDropDownSetting(setting);
                        break;
                    case "date" :
                        setting = $.mrdForm._setDateSetting(setting);
                        break;
                    case "munliselect" :
                        setting = $.mrdForm
                            ._setMunliSelectSetting(setting);
                        break;
                    default :
                        break;
                }
                return setting;
            });
            if (this.allCoulumns == null) {
                this.allCoulumns = new Array();
            }
            this.allCoulumns.concat(tmp);
            return tmp;
        },
        /**
         * 添加textarea类型配置
         */
        _setTextareaSetting: function (columnSettings) {
            var textareaDefaultSetting = {
                /** 以下为textarea类型的独有配置 */
                'rows': "3"// 当type为textarea时，行数
            };
            return $.extend(textareaDefaultSetting, columnSettings);
        },
        /**
         * 添加dropdown类型配置
         */
        _setDropDownSetting: function (columnSettings) {
            var dropdownDefaultSetting = {
                /** 以下为dropdown类型的独有配置* */
                'data': [],// 下拉框的值[[选项1名称，选项1值],[选项2名称，选项2值]....]
                'dropdownType': "",// 下拉框类型
                'dropdownValue': ""// 下拉输入框显示值
            };
            $.extend(dropdownDefaultSetting, columnSettings);
            if (dropdownDefaultSetting.dropdownType == "ajax") {
                var ajaxDropDownSetting = {
                    /** 以下为启用ajax方式独有* */
                    'dropdownType': "ajax",
                    'minLength': 2,
                    'dataType': "json",
                    'url': "",// 查询地址
                    'keyWordName': "k",// 查询参数(后台接收参数名)
                    'method': "post",// 提交方式
                    'success': function (data) {
                        return data.results;
                    }// ajax成功的回调函数，在方法体内需要将返回的数据组装成[[选项1名称，选项1值],[选项2名称，选项2值]....]这样的形式
                };
                return $.extend(ajaxDropDownSetting, dropdownDefaultSetting);
                // return
                // $.extend(dropdownDefaultSetting,ajaxDropDownSetting);
            } else {
                return dropdownDefaultSetting;
            }
        },
        _setMunliSelectSetting: function (columnSettings) {
            var dropDownSettings = this._setDropDownSetting(columnSettings);
            return dropDownSettings;
        },
        /**
         * 添加date类型配置
         */
        _setDateSetting: function (columnSettings) {
            var datePickDefaultSetting = {
                /** 以下属性为date类型的输入框特有属性 */
                format: "yy-mm-dd" // 日期格式，此处为js的日期格式，非java的日期格式
                // 特别注意
            };
            return $.extend(datePickDefaultSetting, columnSettings);
        },
        /**
         * 临时参数，用于统计当前行有多少个td
         */
        _currentColumns: 0,
        /**
         * fieldset编号累加
         */
        _fieldsetNum: 0,
        /**
         * 创建form表单函数
         */
        _createMrdForm: function (dom, settings) {
            var table = this._createTabelForm(dom, settings);
            if (settings.fieldsets != null && settings.fieldsets.leng != 0) {
                $.each(settings.fieldsets, function (i, n) {
                    var container = $("<tr>").appendTo(table);
                    container = $("<td>").appendTo(container);
                    container.attr({
                                       "colspan": settings.numCount * 2
                                   });
                    $.mrdForm._createTabelForm(container, n);
                });
            }
            if(settings.columns.length > 0){
                this._addButtons(table, settings);
            }
            if (settings.module == 'save') {
                // 初始化表单验证引擎
                $("#" + this.formId).validationEngine(
                    settings.form.validate.validateType,
                    settings.form.validate.options);
                // 将表单提交设置成ajaxForm提交
                $('#' + this.formId).submit(function () {
                    $(this).ajaxSubmit(settings.form.ajaxForm);
                    return false;
                });
            }
        },
        /**
         * 创建表单表格，或者根据fieldset创建表单
         */
        _createTabelForm: function (dom, settings) {
            if(settings.columns.length === 0){
                return;
            }
            var table = this._addTable(dom, settings);
            var tr;
            var maxColumnNum = settings.numCount * 2;
            var hiddenControls = new Array();
            if (settings.form.data) {
                this.formDefaultData = settings.form.data.call(this);
                if (typeof(this.formDefaultData) == "string") {//判断是否是json字符串是的话转成Objec
                    this.formDefaultData = $.parseJSON(this.formDefaultData);
                }
            }
            this._currentColumns = 0;
            $.each(settings.columns, function (i, n) {
                if (n.hidden == true || n.hidden == 'true') {
                    hiddenControls.push(n);
                } else {
                    if ((i - hiddenControls.length) == 0
                        || !($.mrdForm._currentColumns < maxColumnNum)
                        || ((maxColumnNum - $.mrdForm._currentColumns) < ($.mrdForm
                                                                              .isEmpty(n.colspan)
                            ? 2 : 2 * n.colspan))) {
                        table.append("<tr></tr>");
                        tr = table.find("tr").last();
                        $.mrdForm._currentColumns = 0;
                    } else {
                        tr = table.find("tr").last();
                    }
                    $.mrdForm._addLabel($.mrdForm._fieldsetNum + "" + i, tr, n,
                                        settings);
                    $.mrdForm._addControl($.mrdForm._fieldsetNum + "" + i, tr,
                                          n, settings);
                }
            });
            this._addHiddenControl(table, hiddenControls);
            return table;
        },
        /**
         * 创建表格主体
         */
        _addTable: function (dom, settings) {
            var fieldsetId = "mf_container" + this._fieldsetNum;
            var tableId = "mf_table" + this._fieldsetNum;
            this._fieldsetNum++;
            this.formContainerId = tableId;
            $("<fieldset>", {
                'id': fieldsetId,
                'class': 'replace-ui-jqgrid ui-widget ui-widget-content ui-corner-all mf_con'
            }).appendTo(dom);
            if (settings.title) {
                $("<div class=\"replace-ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix table_header\"><a href=\"javascript:void(0)\" class=\"replace-ui-jqgrid-titlebar-close HeaderButton tab_button\"><span class=\"ui-icon ui-icon-circle-triangle-s\"></span> </a><span class=\"replace-ui-jqgrid-title\">"
                  + settings.title + "</span></div>").appendTo("#"
                                                               + fieldsetId);
            }
            var tableObj = $("<table>", {
                'id': tableId,
                'class': "mrdTable",
                'width': this.nvl(settings.width, '100%')
            });
            var formObj = null;
            if (settings.module == 'save') {
                formObj = this._addForm(settings);
            } else {
                formObj = $("<form>");
            }
            formObj.appendTo("#" + fieldsetId);
            formObj.css("margin-right", "30px");
            tableObj.appendTo(formObj);
            return $("#" + tableId);
        },
        /**
         * 添加表单
         */
        _addForm: function (settings) {
            var formId = settings.form.id;
            if (this.isEmpty(formId)) {
                formId = "mf_form" + ($("form").size() + 1);
                this.formId = formId;
            }
            return $("<form>", {
                'id': formId,
                'action': settings.form.url
            });
        },
        /**
         * 创建字段的label
         */
        _addLabel: function (index, tr, columnSettings, settings) {
            var tdId = "td_label_" + index;
            if(columnSettings.label){
                $("<td>", {
                    'id': tdId,
                    'width': $.mrdForm.nvl(columnSettings.lwidth, settings.lwidth),
                    'align': $.mrdForm.nvl(columnSettings.lalign, settings.lalign),
                    'valign': $.mrdForm.nvl(columnSettings.lvalign,
                                            settings.lvalign),
                    'height': $.mrdForm
                        .nvl(columnSettings.height, settings.height)
                }).appendTo(tr);
                $("<label>" + columnSettings.label + "：</label>").appendTo("#"
                                                                           + tdId);
            }
            this._currentColumns++;
        },
        /**
         * 创建输入框
         */
        _addControl: function (index, tr, columnSettings, settings) {
            var tdId = "td_control_" + index;
            $("<td>", {
                'id': tdId,
                'class': columnSettings.classId,
                'width': $.mrdForm.nvl(columnSettings.cwidth, settings.cwidth),
                'align': $.mrdForm.nvl(columnSettings.calign, settings.calign),
                'valign': $.mrdForm.nvl(columnSettings.cvalign,
                                        settings.cvalign),
                'height': $.mrdForm
                    .nvl(columnSettings.height, settings.height)
            }).appendTo(tr);
            var tdObj = $("#" + tdId);
            if (columnSettings.colspan) {
                var col = new Number(columnSettings.colspan);
                tdObj.attr("colspan", col * 2 - 1);
                this._currentColumns += col * 2 - 1;
            } else {
                this._currentColumns++;
            }
            switch (columnSettings.type) {
                case "textarea" :
                    $.mrdForm._addTextAreaControl(tdObj, columnSettings);
                    break;
                case "dropdown" :
                    $.mrdForm._addDropdownControl(tdObj, columnSettings);
                    break;
                case "date" :
                    $.mrdForm._addDateControl(tdObj, columnSettings);
                    break;
                case "munliselect" :
                    $.mrdForm._addMunliselectControl(tdObj, columnSettings);
                    break;
                case "file":
                    $.mrdForm._addFileControl(tdObj, columnSettings);
                    break;
                case "spaceHolder":
                    $.mrdForm._addSpaceHolderControl(tdObj, columnSettings);
                    break;
                default :
                    $.mrdForm._addBaseControl(tdObj, columnSettings);

            }
        },
        /**
         * 创建按钮组
         */
        _addButtons: function (table, settings) {
            var baseButtons = new Array();
            var buttonSettings = settings.buttons;
            // 根据表单模式来添加按钮
            if (settings.module == 'save') {
                if (buttonSettings.save) {
                    var buttonSave = $.extend({}, this.buttonSave);
                    //修改保存按钮名字
                    var over = false;
                    $.each(buttonSettings.custom, function (i, n) {
                        if (n.id == "saveButton") {
                            buttonSave = $.extend(buttonSave, n);
                            over = true;
                        }
                    });
                    if (over) {
                        buttonSettings.custom = $.grep(buttonSettings.custom, function (n, i) {
                            return n.id != "saveButton";
                        });
                    }
                    if (!this.isEmpty(buttonSettings.saveEvent)) {
                        buttonSave.click = buttonSettings.saveEvent;
                    }
                    baseButtons.push(buttonSave);
                }
            } else {
                if (buttonSettings.query) {
                    var buttonQuery = $.extend({}, this.buttonQuery);
                    if (!this.isEmpty(buttonSettings.queryEvent)) {
                        buttonQuery.click = buttonSettings.queryEvent;
                    }
                    baseButtons.push(buttonQuery);
                }
            }
            // 添加重置按钮
            if (buttonSettings.reset) {
                var buttonReset = $.extend({}, this.buttonReset);
                // 不再处理自定义重置事件
                // if (!this.isEmpty(buttonSettings.resetEvent))
                // {
                // buttonReset.click =
                // buttonSettings.resetEvent;
                // }
                baseButtons.push(buttonReset);
            }
            var buttons = null;
            if (buttonSettings.custom.length != 0) {
                buttons = baseButtons.concat(buttonSettings.custom);
            } else {
                buttons = baseButtons;
            }
            $("<tr class='mrdBtnTr'><td id='mf_buttons_container'>")
                .appendTo(table);
            $("#mf_buttons_container").attr({
                                                "colspan": settings.numCount * 2,
                                                "align": buttonSettings.position
                                            });
            $.each(buttons, function (i, n) {
                var btnObj = $("<input>", {
                    'type': n.type == 'reset'
                        ? 'reset'
                        : 'button',
                    'id': n.id
                }).button({
                              'disabled': n.disabled,
                              'label': n.value
                          }).css($.mrdForm.buttonBaseCss);
                if (n.type != 'reset') {
                    btnObj.click(n.click);
                }
                btnObj.appendTo($("#mf_buttons_container"));
            });
        },
        /**
         * 添加隐藏表单
         */
        _addHiddenControl: function (table, hiddenArray) {
            $.each(hiddenArray, function (i, n) {
                n.value = $.mrdForm.getControlValue(n.name, n.value);
                $("<input>", {
                    'id': n.id,
                    'name': n.name,
                    'value': n.value,
                    'type': 'hidden'
                }).appendTo(table);
            });
        },
        /**
         * 创建基本输入框
         */
        _addBaseControl: function (td, columnSettings) {
            columnSettings.value = this.getControlValue(columnSettings.name,
                                                        columnSettings.value);
            var input = $("<input>", {
                'id': columnSettings.id,
                'name': columnSettings.name,
                'value': columnSettings.value,
                'type': "text",
                'width': "98%"
            }).addClass(columnSettings.validate).appendTo(td);
            if (columnSettings.readonly == true
                || columnSettings.readonly == 'true') {
                input.attr({
                               //"disabled" : "disabled",
                               "readonly": "readonly"
                           });
                input.css('background-color', 'rgb(235, 235, 228)')
                input.css('border', '1px solid #dddddd');
            }
        },
        /**
         * 创建file输入框
         */
        _addFileControl: function (td, columnSettings) {
            columnSettings.value = this.getControlValue(columnSettings.name,
                                                        columnSettings.value);
            var _file = columnSettings.value;
            if (columnSettings.readonly === undefined || columnSettings.readonly === false
                || columnSettings.readonly === 'false') {
                var input = $("<input>", {
                    'id': columnSettings.id,
                    'name': columnSettings.realName,
                    'value': _file.name,
                    'type': "file",
                    'width': "40%",
                    'onchange': "$(this).next().remove()"
                }).addClass(columnSettings.validate).appendTo(td);
            }

            if (_file) {
                var url = "/business/downloadSingleBizAttachment?atype=declaOffer&aid=" +_file.id;
                var __a = $("<a>", {
                    href: "javascript:$.download(\""+url+"\")",
                    width: '60%',
                    text: _file.name,
                    target: '_blank'
                });
                __a.appendTo(td);
            }
        },
        /**
         * 创建file输入框
         */
        _addSpaceHolderControl: function (td, columnSettings) {
            columnSettings.value = this.getControlValue(columnSettings.name,
                                                        columnSettings.value);
            $("<label>").appendTo(td);
        },
        /**
         * 创建teatarea输入框
         */
        _addTextAreaControl: function (td, columnSettings) {
            columnSettings.value = this.getControlValue(columnSettings.name,
                                                        columnSettings.value);
            var textarea = $("<textarea>", {
                'id': columnSettings.id,
                'name': columnSettings.name,
                'value': columnSettings.value,
                'rows': columnSettings.rows,
                'width': "98%"
            }).addClass(columnSettings.validate).appendTo(td);
            if (columnSettings.readonly == true
                || columnSettings.readonly == 'true') {
                textarea.attr({
                                  "readonly": "readonly",
                                  "disabled": "disabled"
                              });
            }
        },
        /**
         * 创建下拉框
         */
        _addDropdownControl: function (td, columnSettings) {
            columnSettings.value = this.getControlValue(columnSettings.name,
                                                        columnSettings.value);
            var value_input = $("<input>", {
                'id': columnSettings.id,
                'name': columnSettings.name,
                'value': columnSettings.value,
                'type': "hidden"
            });
            var dropdownLabelName = this
                .getDropDwonLabelName(columnSettings.name);
            var _d = columnSettings.data;
            if (_d != undefined && _d != null && _d.lengh != 0) {
                for (var i = 0; i < _d.length; i++) {
                    if (_d[i][1] == columnSettings.value) {
                        columnSettings.dropdownValue = _d[i][0];
                    }
                }
            }
            columnSettings.dropdownValue = this.getControlValue(
                dropdownLabelName, columnSettings.dropdownValue);
            var input = $("<input>", {
                'name': dropdownLabelName,
                'value': columnSettings.dropdownValue,
                'type': "text",
                'width': "98%"
            }).addClass(columnSettings.validate);
            if (columnSettings.readonly == true
                || columnSettings.readonly == 'true') {
                input.attr({
                               "readonly": "readonly",
                               "disabled": "disabled"
                           });
            }
            if (columnSettings.dropdownType == "ajax") {
                this._addAjaxDropdown(input, columnSettings);
            } else {
                this._addBaseDropdown(input, columnSettings);
            }
            this._addDropdownEvent(input, value_input, columnSettings);
            this._addDropdownData(input);
            input.on("change", function () {
                isSelectState = false;
                isfocusState = false;
                if ($.mrdForm.isEmpty(input.val())) {
                    value_input.val("");
                }
            });
            input.on("focusin", function () {
                isSelectState = true;
            });
            input.on("blur", function () {
                if (!$.mrdForm.isEmpty(input.val()) && $.mrdForm.isEmpty(value_input.val())
                    && !isSelectState && !isfocusState) {
                    jw.alert("请不要手动输入下拉框的值！");
                    value_input.val("");
                    input.val("");
                }
            });
            value_input.appendTo(td);
            input.appendTo(td);
        },
        /**
         * 添加多选下拉框控件
         */
        _addMunliselectControl: function (td, columnSettings) {
            this._addDropdownControl(td, columnSettings);
            var input = $(td).find("input").last();
            var value_input = $(td).find("input").first();
            this._addMunliselectEvent(input, value_input, columnSettings);
            this._addMunliselectData(input);
        },
        /**
         * 创建日期输入框
         */
        _addDateControl: function (td, columnSettings) {
            this._addBaseControl(td, columnSettings);
            var datepicker_opt = {
                dateFormat: columnSettings.format,
                showAnim: "slideDown"
            };
            td.children().last().datepicker(datepicker_opt);
        },
        /**
         * 创建基本下拉框
         */
        _addBaseDropdown: function (input, columnSettings) {
            input.autocomplete({
                                   'minLength': columnSettings.minLength ? columnSettings.minLength
                                       : 0,
                                   'source': columnSettings.data
                               });
            input.on("click", function () {
                $(this).autocomplete("search", "");
            });
            if (columnSettings.type == 'dropdown' && columnSettings.itemSelected != undefined) {
                input.on("autocompletechange", function (event, ui) {
                    columnSettings.itemSelected(event, ui);
                });
            }
            if (columnSettings.type === 'dropdown' && columnSettings.itemPick != undefined) {
                input.on("autocompleteselect", function (event, ui) {
                    columnSettings.itemPick(event, ui);
                });
            }
        },
        /**
         * 创建ajax输入框
         */
        _addAjaxDropdown: function (input, columnSettings) {
            input.autocomplete({
                                   minLength: this.nvl(columnSettings.minLength, 0),
                                   source: function (request, response) {
                                       var ac = "";
                                       var ap = "";
                                       var sid = columnSettings.sid;
                                       if (sid != undefined) {
                                           var posi = "0";
                                           if (sid.length <= 2) {
                                               posi = sid.substring(0, 1);
                                               if (undefined != arrP[posi]) {
                                                   ap = arrP[posi].p;
                                                   ac = arrP[posi].c;
                                               }
                                           }
                                       }
                                       /**
                                        * 20141211注释
                                        */
//					var parameter = (new Function("return {\""
//							+ columnSettings.keyWordName + "\":\""
//							+ request.term + "\"}"))();
                                       var parameter = (new Function("return {\""
                                                                     + columnSettings.keyWordName
                                                                     + "\":\""
                                                                     + request.term + "\",\""
                                                                     + "c" + "\":\""
                                                                     + ac + "\",\""
                                                                     + "p" + "\":\""
                                                                     + ap + "\"}"))();
                                       $.ajax(columnSettings.url, {
                                           data: parameter,
                                           dataType: columnSettings.dataType,
                                           type: columnSettings.method,
                                           success: function (data) {
                                               response(columnSettings.success.call(
                                                   columnSettings, data));
                                           },
                                           error: function (XMLHttpRequest, textStatus,
                                                            errorThrown) {
                                               if (textStatus == "parsererror") {
                                                   var type = XMLHttpRequest
                                                       .getResponseHeader("Content-Type");
                                                   if (this.dataType == "json"
                                                       && type == "text/javascript") {
                                                       eval(XMLHttpRequest.responseText);
                                                   }
                                               }
                                           }
                                       });
                                   }
                               });
            if (columnSettings.minLength == 0
                || columnSettings.minLength == '0') {
                input.on("click", function () {
                    $(this).autocomplete("search", "");
                });
            }
        },
        /**
         * 添加下拉框事件
         */
        _addDropdownEvent: function (input, value_input, columnSettings) {
            input.autocomplete({
                                   focus: function (event, ui) {
                                       input.val(ui.item[0]);
                                       isfocusState = true;
                                       return false;
                                   },
                                   select: function (event, ui) {
                                       //	if(dropdownDefaultSetting.dropdownType == "ajax"){
                                       //if(columnSettings.url.indexOf("dropdown-province.do")!=-1)
                                       // { arrP  =ui.item[1]; }else
                                       // if(columnSettings.url.indexOf("dropdown-cityType.do")!=-1){
                                       // arrC=ui.item[1]; } var nlabel = columnSettings.nlabel;
                                       // if(nlabel!=undefined) {
                                       // $("input[name='"+nlabel+"']").val(ui.item[0]); }
                                       // input.val(ui.item[0]); value_input.val(ui.item[1]);
                                       // return false; }
                                       var nlabel = columnSettings.nlabel;
                                       var sid = columnSettings.sid;
                                       if (sid != undefined) {
                                           if (sid.length == 2) {
                                               var kid = sid.substring(1);
                                               var posi = sid.substring(0, 1);
                                               if (kid == "P") {
                                                   if (arrP[posi] == undefined) {
                                                       arrP[posi] =
                                                           new AddrTempParam(ui.item[1], "");
                                                   }
                                                   else {
                                                       arrP[posi].p = ui.item[1];
                                                   }
                                               }
                                               else if (kid == "C") {
                                                   if (arrP[posi] == undefined) {
                                                       arrP[posi] =
                                                           new AddrTempParam("", ui.item[1]);
                                                   }
                                                   else {
                                                       arrP[posi].c = ui.item[1];
                                                   }
                                               }
                                           }
                                       }
                                       if (nlabel != undefined) {
                                           $("input[name='" + nlabel + "']").val(ui.item[0]);
                                       }
                                       //arrP  =ui.item[1];
                                       // arrC=ui.item[1];
                                       input.val(ui.item[0]);
                                       value_input.val(ui.item[1]);
                                       isSelectState = false;
                                       isfocusState = false;
                                       return false;
                                   }
                               });
        },
        /**
         * 给下拉框添加数据
         */
        _addDropdownData: function (input) {
            input.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li>").data("item.autocomplete", item).append("<a>"
                                                                        + item[0]
                                                                        + "</a>").appendTo(ul);
            };
        },
        /**
         * 添加多选下拉框事件
         */
        _addMunliselectEvent: function (input, value_input, columnSettings) {
            input.autocomplete({
                                   focus: function (event, ui) {
                                       return false;
                                   },
                                   select: function (event, ui) {
                                       return true;
                                   }
                               });
        },
        /**
         * 添加多选下拉框数据
         */
        _addMunliselectData: function (input) {
            input.data("autocomplete")._renderItem = function (ul, item) {
                var checkbox = "<a><input type='checkbox' value='" + item[1]
                               + "' />" + item[0] + "</a>";
                var li = $("<li>").data("item.autocomplete", item)
                    .append(checkbox);
                return li.appendTo(ul);
            };
        },
        /**
         * 创建数据表格函数
         *
         * @argument dom 容器
         * @argument settings mrdForm的配置
         */
        _createGrid: function (dom, settings) {
            if (settings.module == 'save') {
                var tr = $("<tr>").insertBefore($("#" + $.mrdForm.formId
                                                  + " > table tr").last());
                var td = $("<td>", {}).appendTo(tr);
                td.attr({
                            "colspan": settings.numCount * 2
                        });
                td.css("padding", "0 5px 0 5px");
                dom = td;
            }
            var gridId = settings.grid.id;
            // 验证id和字段信息是否存在，如果不存在则不再继续创建
            if (this.isEmpty(gridId)) {
                return;
            } else if (this.isEmpty(settings.grid.colModel)) {
                return;
            }
            if ($("#" + gridId).length == 0) {
                $("<table>", {
                    id: gridId
                }).appendTo(dom);
            }
            if ($(settings.grid.pager).length == 0) {
                $("<div>", {
                    id: new String(settings.grid.pager).substr(1)
                }).appendTo(dom);
            }
            var columns = settings.grid.colModel;
            $.each(columns, function (i, n) {
                if (!$.mrdForm.isEmpty(n.dropdown)) {
                    n.formatter = function (cellvalue, options,
                                            rowObject) {
                        for (var i = 0; i < n.dropdown.length; i++) {
                            if (cellvalue == n.dropdown[i][1]) {
                                return n.dropdown[i][0];
                            }
                        }
                        if (cellvalue == null) {
                            return "";
                        }
                        return cellvalue;
                    };
                }
            });
            $("#" + gridId).jqGrid(settings.grid);
        },
        _destroy: function (obj) {
            var objs = obj.children();
            $.each(objs, function (i, n) {
                $(n).remove();
            });
            this.formContainerId = null;
            this.formId = null;
            this.mrdFormSettings = {};
        },
        _build: function (dom, options) {
            var setting = $.mrdForm._initSetting(options);
            this._createMrdForm(dom, setting);
            this._createGrid(dom, setting);
        },
        /**
         * 获取下拉框显示值字段名
         */
        getDropDwonLabelName: function (dropdownName) {
            return "control_" + dropdownName.replace(/\./g, "_") + "_dropdown";
        },
        /**
         * 获取默认值
         */
        getControlValue: function (name, value) {
            try {
                var value_tmp = this.formDefaultData;
                if (name) {
                    var ns = name.split("\.");
                    for (var i = 0; i < ns.length; i++) {
                        value_tmp = value_tmp[ns[i]];
                    }
                    if (value_tmp) {
                        return value_tmp;
                    } else {
                        return value;
                    }
                }
            } catch (e) {
                return value;
            }
        },
        /**
         * 辅助函数，如果str1为空则输出str2否则输出str1
         */
        nvl: function (str1, str2) {
            if (str1) {
                return str1;
            } else {
                return str2;
            }
        },
        /**
         * 辅助函数，用于判断str是否为空,空则输出true,不为空则输出false
         */
        isEmpty: function (str) {
            if (str) {
                return false;
            } else {
                return true;
            }
        },
        /**
         * 重置grid的大小
         */
        resizeGrid: function () {
            var selector = $("#" + this.mrdFormSettings.grid.id);
            $(window).resize(function () {
                $(selector).setGridWidth(
                    $(window).width()
                    - $(selector).getGridParam('scrollOffset'),
                    true);
            });
            return $(selector);
        },
        /**
         * 通过ajax获取下拉框的值，一般用于获取常量值，如使用状态，类型等
         */
        ajaxdp: function (url) {
            var results = null;
            $.ajax({
                       "url": url,
                       async: false,
                       "success": function (data) {
                           results = data.results;
                       },
                       error: function (XMLHttpRequest, textStatus,
                                        errorThrown) {
                           if (textStatus == "parsererror") {
                               var type = XMLHttpRequest
                                   .getResponseHeader("Content-Type");
                               if (this.dataType == "json"
                                   && type == "text/javascript") {
                                   eval(XMLHttpRequest.responseText);
                               }
                           }
                       }
                   });
            return results;
        },
        /**
         * 从下拉框选项中根据真实值获取显示值
         */
        dropdownShowValue: function (dropdownOptions, dropdownValue) {
            var data = "";
            $.each(dropdownOptions, function (i, n) {
                if (dropdownValue == n[1]) {
                    data = n[0];
                }
            });
            return data;
        }
    });
    var methods = {
        hide: function (selector) {
            return $(selector).hide();
        },
        show: function (selector) {
            return $(selector).show();
        },
        disable: function (selector) {
            return $(selector).button('disable');
        },
        enable: function (selector) {
            return $(selector).button('enable');
        },
        resize: function () {
            return $.mrdForm.resizeGrid();
        },
        rebuild: function (options) {
            $.mrdForm._destroy($(this));
            $.mrdForm._build($(this), options);
        },
        destroy: function () {
            return $.mrdForm._destroy($(this));
        },
        formVal: function (fieldName) {
            return $("#" + $.mrdForm.formContainerId + " input[name='"
                     + fieldName + "']").val();
        },
        refreshGrid: function () {
            var gridSelect = "#" + $.mrdForm.mrdFormSettings.grid.id;
            var filters = $.mrdForm.filterString();
            // 如果没有查询条件，则返回
            if (!$.mrdForm.isEmpty(filters)) {
                var postData = $(gridSelect).jqGrid("getGridParam", "postData");// 获取将要提交的数据
                $.extend(postData, {
                    filters: filters
                });// 将filters插入将要提交的数据
            }
            $(gridSelect).jqGrid("setGridParam", {
                search: true
                // 将jqGrid的search选项设为true
            }).trigger("reloadGrid", [{
                page: 1
            }]); // 重新载入Grid表格
        }
    };
    /**
     * mrdForm对象，参数为方法名，获取初始化对象
     */
    $.fn.mrdForm = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(
                arguments, 1));
        } else if (typeof method === 'object' || !method) {
            var obj = this.each(function () {
                $.mrdForm._build($(this), method);
            });
            obj.mrdForm("resize");
            return obj;
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.tooltip');
        }
    };
}(jQuery));
$.jqGrid = {};
$.jqGrid.custom = {
    constants: {
        //存储jqgrid 按钮的event
        dataGridButtonEvent: {},
        /**
         * jqgrid行的按钮配置
         */
        defaultGridButtonConfig: {
            key: "",
            /**
             * 是否隐藏，接受boolean类型或者boolean的字符串或者函数，其中函数的返回值控制是否展示按钮
             */
            hide: false,
            class: "",
            value: "按钮",
            style: ""
        }
    },
    formatter: {
        /**
         * jqGrid的formatter扩展，扩展按钮组
         * 需要在colModel中添加buttons配置，如下:
         * [
         * {value:'按钮名称',click:function(gridId,rowId,rowData){console.log('点击事件，参数为行的数据');}},
         * {value:'按钮名称',click:function(gridId,rowId,rowData){console.log('点击事件，参数为行的数据');}}
         * ]
         * @param cellvalue
         * @param options
         * @param rowObject
         * @returns {string}
         */
        button: function (cellvalue, options, rowObject) {
            var buttonConfig = options.colModel.buttons;
            if (!buttonConfig || buttonConfig.length == 0) {
                console.error(
                    "未定义按钮组或为空，请在确认字段配置中加入了buttons，并对其定义，格式为：{value:'按钮名称',click:function(row){console.log('点击事件，参数为行的数据');}}");
            }
            var btnStr = "";
            $.each(buttonConfig, function (i, n) {
                var config = $.extend({}, $.jqGrid.custom.constants.defaultGridButtonConfig, n);
                if (!n.key) {
                    console.error("表格中的按钮组列的按钮未配置key属性,普通字符串配置为：" + JSON.stringify(n));
                }
                if (!n.click) {
                    console.error("表格中的按钮组列的按钮未配置点击事件请配置click属性");
                }
                //是否显示按钮
                if (n.hide === undefined) {
                    config.hide = false;
                } else if (typeof(n.hide) === "function") {
                    config.hide = n.hide(rowObject);
                } else if (n.hide === "true") {
                    config.hide = true;
                }
                if (!config.hide) {
                    var btn = $(
                        "<input type=\"button\" class=\"ui-button ui-widget ui-state-default ui-corner-all ui-state-focus grid-button\" role=\"button\" aria-disabled=\"false\" >");
                    btn.attr("key", config.key);
                    btn.val(config.value);
                    btn.addClass(config.class);
                    btn.css(config.style);
                    btnStr += btn[0].outerHTML;
                    $.jqGrid.custom.constants.dataGridButtonEvent[config.key] = config.click;
                }
            });
            return btnStr;
        }
    }
};

$(document).ready(function () {
    //jqgrid按钮组扩展的按钮点击事件的触发实现
    $("body").on('click', ".ui-jqgrid .grid-button", function (event) {
        var id = $(event.target).parents("tr:first").attr("id");
        var gridId = $(event.target).parents(".ui-jqgrid").attr("id").substr(5);
        var rowData = $("#" + gridId).jqGrid("getRowData", id);
        $.jqGrid.custom.constants.dataGridButtonEvent[$(event.target).attr("key")].call(
            event.target, gridId, id, rowData);
        return false;
    });
});
